/**
 * 目的：物体的缩放与旋转
 */
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

let scene, camera, renderer, controls, parentCube
// 初始化场景和渲染器
function initScene() {
  console.log(111)
  scene = new THREE.Scene()
  // 创建渲染器，指定canvas元素
  const canvas = document.querySelector('#c')
  renderer = new THREE.WebGLRenderer({ antialias: true, canvas })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)
}
function initCamera() {
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100)
  camera.position.set(5, 5, 5)
  camera.lookAt(0, 0, 0)
  scene.add(camera)
}
function createCube() {
  const geometry = new THREE.BoxGeometry(1, 1, 1)
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
  const cube = new THREE.Mesh(geometry, material)
  parentCube = new THREE.Mesh(geometry, material)
  // 确保 cube 正常创建
  if (!cube) {
    console.error('Cube creation failed')
    return
  }
  cube.position.set(0, 0, 0) // 将物体放置在原点
  parentCube.position.set(0, 0, 2)
  // parentCube.scale.set(2,2,2)
  scene.add(cube)
  cube.add(parentCube)
}
// 辅助器
function axesHelper() {
  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
}
function initControls() {
  controls = new OrbitControls(camera, renderer.domElement)
}
function animate() {
  requestAnimationFrame(animate)
  // 旋转父物体 parentCube
  parentCube.rotation.x += 0.02
  parentCube.rotation.y += 0.02
  controls.update()
  renderer.render(scene, camera)
}
function init() {
  initScene()
  initCamera()
  createCube()
  axesHelper()
  initControls()
  animate()
}
// 启动应用
init()

// 响应窗口大小变化
window.addEventListener('resize', onWindowResize)

function onWindowResize() {
  // 更新相机的宽高比
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()

  // 更新渲染器的尺寸
  renderer.setSize(window.innerWidth, window.innerHeight)
}

// 将场景对象挂载到 window 方便调试
window.scene = scene
